let path = require('path')
let { CleanWebpackPlugin } = require('clean-webpack-plugin');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let {  DefinePlugin } = require('webpack')
let { VueLoaderPlugin } = require('vue-loader/dist/index')
let webpack = require("webpack")

const ENV = process.env.NODE_ENV
let config = {
  // 设置模式
  // development 开发阶段
  // production 准备打包上线的时候
  mode: 'development',
  target: 'web',
  // devtools: "source-map",
  // watch: true,
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/bundle.js',
  },
  resolve: {
    extensions: 
    [".js", ".json", ".mjs", ".wmjs", ".vue", ".ts", ".jsx", ".tsx"],
    alias: {
      "js": path.resolve(__dirname, './src/js'),
      "@": path.resolve(__dirname, './src')
    }
  },
  module: {
    rules: [
      {
        test:/\.css$/i,
        use: ['style-loader', 'css-loader']
      },
      {
        test: /\.less/i,
        use: ['style-loader', 'css-loader', 'less-loader']
      },
       // webpack5的写法
       {
        test: /\.(png|jpg|gif)$/,
        type: 'asset',
        generator: {
          filename: 'img/[name].[hash:8].[ext]'
        },
        parser: {
          dataUrlCondition: {
            maxSize: 100 * 1024 // 4kb
          }
        }

      },
      {
        test: /\.(ttf|woff|woff2)$/,
        type: 'asset/resource',
        generator: {
          filename: 'font/[name].[hash:8].[ext]'
        },

      },
      {
        test: /\.js$/,
        loader: 'babel-loader'
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html',
      title: '哈哈哈',
      fliename: 'test.html'
    }),
    new DefinePlugin({
      BASE_URL: '"./"',
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false
    }),
    new VueLoaderPlugin({}),
  ]
}
if (ENV === 'production') {
  config.mode = 'production'
  // 自动清理dist目录中重复的文件
  config.plugins.push(new CleanWebpackPlugin())
}
if (ENV === 'development') {
  config.mode = 'production'
  // 自动清理dist目录中重复的文件
  config.devServer =  {
    // contentBase: './public'
    static: './dist',
    hot: true, //热更新
    port: 8000,
    open: true,
    proxy: {
      "/api": {
        target: 'http://localhost:8888',
        pathRewrite:{
          '^/api': ''
        },
        secure: false,
        changeOrigin: true
      }
    }
  },
   // 用于热更新的两个插件
    // 给每一个模块添加一个名字
    config.plugins.push(new webpack.NamedModulesPlugin())
    // 启用热更新，启动本地服务器中的websocket长连接
    config.plugins.push(new webpack.HotModuleReplacementPlugin())
}
// const CopyPlugin = require("copy-webpack-plugin");
module.exports = config